package cn.edu.cdp.jxgl_springboot_web.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private final static String secret = "SD4F#$%";
    private final static Calendar calendar = Calendar.getInstance();


    /**
     * 生成 JWT 令牌
     */
    public static String generateJwt(Map<String, Object> headers) {
        calendar.add(Calendar.MINUTE, 30);
        Date expires = calendar.getTime();
        return JWT.create()
                // 第一部分 header
                .withHeader(headers)
                // 第二部分 payload
                .withClaim("author", "Rain Brook")
                .withExpiresAt(expires)
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 解析 JWT 令牌
     * @param jwt JWT 令牌字符串
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static DecodedJWT parseJwt(String jwt) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = verifier.verify(jwt);
        System.out.println(decodedJWT.getClaim("author").asString());
        System.out.println("过期时间：" + decodedJWT.getExpiresAt());
        return decodedJWT;
    }
}
